﻿using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;

public static class SpriteAnimatorExtension
{
    public static void LoadAnimations(this SpriteAnimator anim, string resourceFolderPath)
    {
        SpriteModelImportSetting setting = JsonUtility.FromJson<SpriteModelImportSetting>(Resources.Load<TextAsset>(resourceFolderPath + "/ImportSetting").text);
        List<SpriteAnimator.Animation> animations = new List<SpriteAnimator.Animation>();
        foreach (SpriteModelImportSetting.Animation animation in setting.animations)
        {
            SpriteAnimator.Animation item = new SpriteAnimator.Animation {
                name = animation.name,
                loop = animation.loop
            };
            foreach (SpriteModelImportSetting.Frame frame in animation.frames)
            {
                string path = resourceFolderPath + "/" + frame.filePath.Replace(".png", string.Empty);
                Sprite sprite = Resources.Load<Sprite>(path);
                if (sprite == null)
                {
                    object[] args = new object[] { path };
                    Debug.LogWarningFormat("Could not find frame '{0}'", args);
                }
                else
                {
                    SpriteAnimator.Frame frame2 = new SpriteAnimator.Frame {
                        sprite = sprite,
                        duration = frame.duration
                    };
                    item.frames.Add(frame2);
                }
            }
            animations.Add(item);
        }
        anim.SetAnimations(animations);
    }
}

